<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="为什么要在nextTick回调后操作DOM？js回调函数怎么关联上DOM的？">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解nextTick">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="为什么要在nextTick回调后操作DOM？js回调函数怎么关联上DOM的？">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/nextTick_page.png">
<meta property="og:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/nextTick_and_microtask.png">
<meta property="article:published_time" content="2021-05-29T04:14:12.000Z">
<meta property="article:modified_time" content="2021-11-28T11:05:49.117Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/nextTick_page.png">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入理解nextTick | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#nextTick%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">nextTick什么时候用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nextTick-%E7%9A%84%E6%9C%AC%E8%B4%A8"><span class="nav-number">2.</span> <span class="nav-text">nextTick()的本质</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BB%93%E5%90%88EventLoop%E7%90%86%E8%A7%A3nextTick"><span class="nav-number">2.1.</span> <span class="nav-text">结合EventLoop理解nextTick()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nextTick-%E9%80%9A%E8%BF%87MutataionObsever%E7%9B%91%E5%90%ACDOM%E7%9A%84%E6%9B%B4%E6%96%B0"><span class="nav-number">2.2.</span> <span class="nav-text">nextTick()通过MutataionObsever监听DOM的更新</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#nextTick-%E6%9C%AC%E8%B4%A8%E5%B0%B1%E6%98%AF%E5%BE%80%E5%BE%AE%E4%BB%BB%E5%8A%A1%E9%98%9F%E5%88%97%E4%B8%AD%E8%BF%BD%E5%8A%A0%E6%89%A7%E8%A1%8C%E5%87%BD%E6%95%B0"><span class="nav-number">2.3.</span> <span class="nav-text">nextTick()本质就是往微任务队列中追加执行函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%80%9A%E8%BF%87%E5%AF%B9%E6%AF%94%EF%BC%8C%E8%AE%A4%E6%B8%85%E8%87%AA%E5%B7%B1"><span class="nav-number">2.4.</span> <span class="nav-text">通过对比，认清自己</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#nextTick%E4%B8%8Eprocess-nextTick-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">2.4.1.</span> <span class="nav-text">nextTick与process.nextTick()的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nextTick%E4%B8%8EjQuery-ready-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">2.4.2.</span> <span class="nav-text">nextTick与jQuery.ready()的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%85%A8%E5%B1%80%E7%9A%84Vue-nextTick%E4%B8%8E%E7%BB%84%E4%BB%B6%E5%86%85this-nextTick%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">2.4.3.</span> <span class="nav-text">全局的Vue.nextTick与组件内this.nextTick的区别</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nextTick%E4%B8%8ErequestAnimationFrame-%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-number">2.4.4.</span> <span class="nav-text">nextTick与requestAnimationFrame()的关系</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#nextTick%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-number">3.</span> <span class="nav-text">nextTick实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%BA%90%E7%A0%81%E8%B5%B0%E8%AF%BB"><span class="nav-number">3.1.</span> <span class="nav-text">源码走读</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%BB%E7%BB%93%E6%A6%82%E8%BF%B0"><span class="nav-number">3.2.</span> <span class="nav-text">总结概述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number">4.</span> <span class="nav-text">参考</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%AA%E8%A7%A3%E5%86%B3%E7%9A%84%E7%96%91%E6%83%91"><span class="nav-number">5.</span> <span class="nav-text">未解决的疑惑</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解nextTick
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-05-29 12:14:12" itemprop="dateCreated datePublished" datetime="2021-05-29T12:14:12+08:00">2021-05-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-11-28 19:05:49" itemprop="dateModified" datetime="2021-11-28T19:05:49+08:00">2021-11-28</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/Vue2%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3/" itemprop="url" rel="index"><span itemprop="name">Vue2深入理解</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>8.3k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>8 分钟</span>
    </span>
</div>

            <div class="post-description">为什么要在nextTick回调后操作DOM？js回调函数怎么关联上DOM的？</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="nextTick什么时候用"><a href="#nextTick什么时候用" class="headerlink" title="nextTick什么时候用"></a>nextTick什么时候用</h2><p>道理讲再多，不如带你真真切切的踩个坑。如下图所示，一个门店后厨的统计页面，在第一个“后厨出菜统计”模块，要绘制每个厨师出菜比例的饼图。</p>
<p><img src="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/nextTick_page.png"></p>
<p>既然Vue是双向数据绑定的，我们直接把响应数据赋值给data后，视图理应就会更新，可我们紧接着通过DOM对象绘制图表的时候，却报错找不到DOM元素。显然Vue的数据赋值后，没有立即去更新DOM。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">&quot;title&quot;</span>&gt;</span>后厨出菜统计<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;cook-item&quot;</span> </span></span><br><span class="line"><span class="tag">   <span class="attr">v-for</span>=<span class="string">&quot;(cook,index) in cookList&quot;</span> </span></span><br><span class="line"><span class="tag">   <span class="attr">:key</span>=<span class="string">&quot;&#x27;chef_list_&#x27;+cook.oid&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 出菜信息 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 出菜图表 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&quot;flex: 1;background-color: #f8f8f8;border-radius: 6px;&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">canvas</span> <span class="attr">:id</span>=<span class="string">&quot;&#x27;pie_&#x27; + cook.oid&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">canvas</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">import</span> F2 <span class="keyword">from</span> <span class="string">&#x27;@antv/f2&#x27;</span>;</span></span><br><span class="line"><span class="javascript"><span class="keyword">const</span> axios = <span class="built_in">require</span>(<span class="string">&#x27;axios&#x27;</span>).default;</span></span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="comment">// 动态构造饼图</span></span></span><br><span class="line"><span class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">makePieChart</span>(<span class="params">list, containerId</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">  <span class="comment">// ....</span></span></span><br><span class="line"><span class="javascript">  <span class="keyword">const</span> pieChart = <span class="keyword">new</span> F2.Chart(&#123;</span></span><br><span class="line">    id: containerId,</span><br><span class="line"><span class="javascript">    pixelRatio: <span class="built_in">window</span>.devicePixelRatio,</span></span><br><span class="line"><span class="javascript">    padding: [<span class="number">20</span>, <span class="string">&#x27;auto&#x27;</span>]</span></span><br><span class="line">  &#125;);</span><br><span class="line"><span class="javascript">  <span class="comment">// ...</span></span></span><br><span class="line">  pieChart.render();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="javascript">  name: <span class="string">&#x27;cookReport&#x27;</span>,</span></span><br><span class="line">  props: &#123;</span><br><span class="line"><span class="javascript">    storeCode: <span class="built_in">String</span>,  <span class="comment">// 门店编码</span></span></span><br><span class="line"><span class="javascript">    date: <span class="built_in">String</span>  <span class="comment">// 统计日期</span></span></span><br><span class="line">  &#125;,</span><br><span class="line"><span class="javascript">  <span class="function"><span class="title">data</span>(<span class="params"></span>)</span> &#123;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">return</span> &#123;</span></span><br><span class="line">      cookList: []</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"><span class="javascript">  <span class="function"><span class="title">mounted</span>(<span class="params"></span>)</span> &#123;</span></span><br><span class="line"><span class="javascript">    <span class="comment">// 挂载完成后，发起请求数据</span></span></span><br><span class="line"><span class="javascript">    axios.get(<span class="string">`<span class="subst">$&#123;process.env.VUE_APP_BASE_URL&#125;</span>/report?date=<span class="subst">$&#123;<span class="built_in">this</span>.date&#125;</span>&amp;storeCode=<span class="subst">$&#123;<span class="built_in">this</span>.storeCode&#125;</span>`</span>).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 赋值</span></span></span><br><span class="line"><span class="javascript">        <span class="built_in">this</span>.cookList = res.data</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 直接调用</span></span></span><br><span class="line"><span class="javascript">        <span class="built_in">this</span>.cookList.forEach(<span class="function"><span class="params">cook</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">          makePieChart(cook.pieDataList, <span class="string">`pie_<span class="subst">$&#123;cook.oid&#125;</span>`</span>)</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>F2图表绘制报错：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Uncaught (<span class="keyword">in</span> promise) <span class="built_in">TypeError</span>: Cannot read property <span class="string">&#x27;currentStyle&#x27;</span> <span class="keyword">of</span> <span class="literal">null</span></span><br><span class="line">    at getStyle (f2.js?e004:<span class="number">765</span>)</span><br><span class="line">    at getWidth (f2.js?e004:<span class="number">769</span>)</span><br><span class="line">    at Canvas._initCanvas (f2.js?e004:<span class="number">9848</span>)</span><br><span class="line">    at <span class="keyword">new</span> Canvas (f2.js?e004:<span class="number">9801</span>)</span><br><span class="line">    at createCanvas (f2.js?e004:<span class="number">10031</span>)</span><br><span class="line">    at Chart._initCanvas (f2.js?e004:<span class="number">10490</span>)</span><br><span class="line">    at Chart._init (f2.js?e004:<span class="number">10567</span>)</span><br><span class="line">    at <span class="keyword">new</span> Chart (f2.js?e004:<span class="number">10606</span>)</span><br><span class="line">    at makePieChart (StoreReport.vue?<span class="number">8e92</span>:<span class="number">161</span>)</span><br><span class="line">    at <span class="built_in">eval</span> (StoreReport.vue?<span class="number">8e92</span>:<span class="number">293</span>)</span><br></pre></td></tr></table></figure>

<p>这是因为Vue采取的是异步更新策略，我们把图表绘制的代码写在nextTick里，能正常运行了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">mounted</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">  <span class="comment">// 挂载完成后，发起请求数据</span></span><br><span class="line">  axios.get(<span class="string">`<span class="subst">$&#123;process.env.VUE_APP_BASE_URL&#125;</span>/report?date=<span class="subst">$&#123;<span class="built_in">this</span>.date&#125;</span>&amp;storeCode=<span class="subst">$&#123;<span class="built_in">this</span>.storeCode&#125;</span>`</span>).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 赋值</span></span><br><span class="line">      <span class="built_in">this</span>.cookList = res.data</span><br><span class="line">      <span class="comment">// 等待DOM更新完成后，再调用</span></span><br><span class="line">      <span class="built_in">this</span>.$nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.cookList.forEach(<span class="function"><span class="params">cook</span> =&gt;</span> &#123;</span><br><span class="line">          makePieChart(cook.pieDataList, <span class="string">`pie_<span class="subst">$&#123;cook.oid&#125;</span>`</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="nextTick-的本质"><a href="#nextTick-的本质" class="headerlink" title="nextTick()的本质"></a><code>nextTick()</code>的本质</h2><ul>
<li>结合上面的例子，再理解官方文档的解释，就一目了然了：</li>
</ul>
<blockquote>
<p>在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。</p>
</blockquote>
<p>那么问题来了，我们不禁要思考nextTick回调函数的本质是什么？</p>
<ol>
<li>nextTick，单词next我知道是”下一个”，那什么是tick？</li>
<li>nextTick明明是JS代码，它怎么就知道DOM什么时候更新呢？又是谁去通知它呢？</li>
<li>nextTick是钩子函数嘛，能否像mounted/watch生命周期函数的方式来使用？反正DOM更新就会通知调用不是嘛？</li>
</ol>
<h3 id="结合EventLoop理解nextTick"><a href="#结合EventLoop理解nextTick" class="headerlink" title="结合EventLoop理解nextTick()"></a>结合EventLoop理解<code>nextTick()</code></h3><p>解答第一个问题，就不得不提事件循环机制。</p>
<p>众所周知，事件循环(EventLoop)是JS协调异步程序的机制，不知道的，可参考一下我另外一篇文章（<a target="_blank" rel="noopener" href="http://lianghuilin.gitee.io/murmur/interview_questions/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/">深入理解事件循环机制</a>）。<br>异步程序中又分为宏任务和微任务，宏任务通常是和浏览器级别的，比如定时器/轮询器/XHR等；微任务通常是ECMAScript级别的，比如promise/await+async/mutationObserver/processe.nextTick等；<br>宏任务和微任务都是以队列(queue)的数据结构存在，宿主环境轮询检查执行栈(CallStack)的清空情况，然后逐个放入宏任务执行，当前宏任务完后执行紧接着会执行微任务。</p>
<p>现在可以回答第一个问题了，每执行一个宏任务，就是一个tick。而<code>nextTick()</code>在语境上，可以理解成”在下一个宏任务执行之前的回调函数”。</p>
<h3 id="nextTick-通过MutataionObsever监听DOM的更新"><a href="#nextTick-通过MutataionObsever监听DOM的更新" class="headerlink" title="nextTick()通过MutataionObsever监听DOM的更新"></a><code>nextTick()</code>通过MutataionObsever监听DOM的更新</h3><p>接着解答第二个问题，DOM的增删改查操作是同步执行的，对于DOM变化的监听提供的MutationObsever API是异步的，并且属于微任务。<br>一个简单的MutationObsever示例：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;container&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="comment">// 厨师列表</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> cookList = [&#123;</span></span><br><span class="line"><span class="javascript">            name: <span class="string">&#x27;斯蒂芬周&#x27;</span>,</span></span><br><span class="line">            oid: 10081</span><br><span class="line">        &#125;,&#123;</span><br><span class="line"><span class="javascript">            name: <span class="string">&#x27;鸡姐&#x27;</span>,</span></span><br><span class="line">            oid: 10082</span><br><span class="line">        &#125;,&#123;</span><br><span class="line"><span class="javascript">            name: <span class="string">&#x27;唐牛&#x27;</span>,</span></span><br><span class="line">            oid: 10083</span><br><span class="line">        &#125;];</span><br><span class="line"><span class="javascript">        <span class="comment">// 模板容器</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">let</span> $container = <span class="built_in">document</span>.getElementById(<span class="string">&#x27;container&#x27;</span>);</span></span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 当容器内的chart DOM插入后，打印日志</span></span></span><br><span class="line"><span class="javascript">        <span class="keyword">new</span> MutationObserver(<span class="function">() =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(<span class="string">&#x27;大厨已就绪，可以进行下一步图表绘制工作！&#x27;</span>)</span></span><br><span class="line">        &#125;).observe($container, &#123;</span><br><span class="line"><span class="javascript">            childList: <span class="literal">true</span>,</span></span><br><span class="line"><span class="javascript">            subtree: <span class="literal">true</span></span></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line"><span class="javascript">        <span class="comment">// 遍历数组，插入chart DIV</span></span></span><br><span class="line"><span class="javascript">        cookList.forEach(<span class="function"><span class="params">cook</span> =&gt;</span> &#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">let</span> cookDiv = <span class="built_in">document</span>.createElement(<span class="string">&#x27;div&#x27;</span>);</span></span><br><span class="line"><span class="javascript">            cookDiv.setAttribute(<span class="string">&#x27;id&#x27;</span>,<span class="string">&#x27;cook_&#x27;</span> + cook.oid);</span></span><br><span class="line">            cookDiv.textContent = cook.name;</span><br><span class="line">            $container.appendChild(cookDiv);</span><br><span class="line">        &#125;);</span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="nextTick-本质就是往微任务队列中追加执行函数"><a href="#nextTick-本质就是往微任务队列中追加执行函数" class="headerlink" title="nextTick()本质就是往微任务队列中追加执行函数"></a><code>nextTick()</code>本质就是往微任务队列中追加执行函数</h3><p>接下来看第三个问题：如果像生命周期函数一样，提前注册nextTick是否可行呢？答案是否定的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">mounted</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">  <span class="comment">// 先注册nextTick</span></span><br><span class="line">  <span class="built_in">this</span>.$nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;DOM ready&#x27;</span>)</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  axios.get(<span class="string">`<span class="subst">$&#123;process.env.VUE_APP_BASE_URL&#125;</span>/report?date=<span class="subst">$&#123;<span class="built_in">this</span>.date&#125;</span>&amp;storeCode=<span class="subst">$&#123;<span class="built_in">this</span>.storeCode&#125;</span>`</span>).then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 响应后对数据进行赋值</span></span><br><span class="line">      <span class="built_in">this</span>.cookList = res.data</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">&#x27;data assign&#x27;</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出的结果：没等数据赋值，<code>nextTick()</code>就先执行了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt; DOM ready</span><br><span class="line">&gt; data assign</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/lianghuilin/blog-image-warehouse/raw/master/nextTick_and_microtask.png"></p>
<p>结论：<code>MutataionObsever</code>和<code>nextTick</code>都是微任务，在队列中按顺序执行。所以在业务代码中，数据赋值与<code>nextTick()</code>总是成对出现，并且<code>nextTick</code>必须在数据赋值后面，不能像钩子函数一样提前注册。</p>
<h3 id="通过对比，认清自己"><a href="#通过对比，认清自己" class="headerlink" title="通过对比，认清自己"></a>通过对比，认清自己</h3><h4 id="nextTick与process-nextTick-的区别"><a href="#nextTick与process-nextTick-的区别" class="headerlink" title="nextTick与process.nextTick()的区别"></a><code>nextTick</code>与<code>process.nextTick()</code>的区别</h4><p><code>process.nextTick</code>是node.js的API，和<code>Vue.nextTick</code>一样，都是往微任务追加执行函数</p>
<h4 id="nextTick与jQuery-ready-的区别"><a href="#nextTick与jQuery-ready-的区别" class="headerlink" title="nextTick与jQuery.ready()的区别"></a><code>nextTick</code>与<code>jQuery.ready()</code>的区别</h4><p>当我和后端小哥用厨师图表渲染的例子，讲解<code>nextTick</code>时，他当下反应是，“哦！这个我知道，和jQuery.ready()一样嘛！”，我当时是一脸的黑人问号表情。这两者还是不一样的，<code>jQuery.ready()</code>是jQuery实例挂载到window的回调函数，函数里面就可以通过jQuery来操作DOM了。而<code>Vue.nextTick()</code>是响应数据绑定的视图更新后的回调函数，函数里面可以操作DOM。</p>
<h4 id="全局的Vue-nextTick与组件内this-nextTick的区别"><a href="#全局的Vue-nextTick与组件内this-nextTick的区别" class="headerlink" title="全局的Vue.nextTick与组件内this.nextTick的区别"></a>全局的<code>Vue.nextTick</code>与组件内<code>this.nextTick</code>的区别</h4><p>当前组件和与全局Vue实例都指向<code>src/core/util/next-tick.js</code>同一个<code>nextTick()</code>函数</p>
<h4 id="nextTick与requestAnimationFrame-的关系"><a href="#nextTick与requestAnimationFrame-的关系" class="headerlink" title="nextTick与requestAnimationFrame()的关系"></a><code>nextTick</code>与<code>requestAnimationFrame()</code>的关系</h4><p>还是要回到EventLoop机制：</p>
<ol>
<li>执行栈(Call Stack)清空后，放入宏任务队列排在最前面的task，并执行它；</li>
<li>执行当前宏任务后，检查是否存在微任务(<code>Microtask</code>)，如果有，则轮询执行，直到清空微任务队列（包含嵌套产生的微任务）；</li>
<li>检查是否进行浏览器渲染；</li>
<li>如需渲染，先调用requestAnimationFrame函数；</li>
<li>然后执行浏览器更新渲染；</li>
<li>最后执行requestIdleCallback函数；</li>
<li>重复以上步骤</li>
</ol>
<p>可见，nextTick只是微任务队列中普通的函数，就是按顺序执行。而<code>requestAnimationFrame()</code>取决于本次轮询是否要进行更新渲染，在需要更新渲染前，调用执行。</p>
<h2 id="nextTick实现原理"><a href="#nextTick实现原理" class="headerlink" title="nextTick实现原理"></a>nextTick实现原理</h2><h3 id="源码走读"><a href="#源码走读" class="headerlink" title="源码走读"></a>源码走读</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* @flow */</span></span><br><span class="line"><span class="comment">/* globals MutationObserver */</span></span><br><span class="line"><span class="keyword">import</span> &#123; noop &#125; <span class="keyword">from</span> <span class="string">&#x27;shared/util&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; handleError &#125; <span class="keyword">from</span> <span class="string">&#x27;./error&#x27;</span></span><br><span class="line"><span class="keyword">import</span> &#123; isIE, isIOS, isNative &#125; <span class="keyword">from</span> <span class="string">&#x27;./env&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 标识-是否使用微任务执行回调函数</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">let</span> isUsingMicroTask = <span class="literal">false</span> </span><br><span class="line"><span class="comment">// 数组-回调函数列表</span></span><br><span class="line"><span class="keyword">const</span> callbacks = []  </span><br><span class="line"><span class="comment">// 标识-是否有回调函数在执行中</span></span><br><span class="line"><span class="keyword">let</span> pending = <span class="literal">false</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 轮询callbacks数组，执行每个回调函数，并清空数组</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flushCallbacks</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  pending = <span class="literal">false</span></span><br><span class="line">  <span class="comment">// 复制到局部变量</span></span><br><span class="line">  <span class="keyword">const</span> copies = callbacks.slice(<span class="number">0</span>)</span><br><span class="line">  <span class="comment">// 清空原数组</span></span><br><span class="line">  callbacks.length = <span class="number">0</span></span><br><span class="line">  <span class="comment">// 轮询执行每个回调函数</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; copies.length; i++) &#123;</span><br><span class="line">    copies[i]()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义主逻辑的timerFunc方法</span></span><br><span class="line"><span class="keyword">let</span> timerFunc</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (<span class="keyword">typeof</span> <span class="built_in">Promise</span> !== <span class="string">&#x27;undefined&#x27;</span> &amp;&amp; isNative(<span class="built_in">Promise</span>)) &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 判断是否支持Promise</span></span><br><span class="line"><span class="comment">   */</span> </span><br><span class="line">  <span class="keyword">const</span> p = <span class="built_in">Promise</span>.resolve()</span><br><span class="line">  <span class="comment">// 以Promise.then来处理flushCallbacks函数</span></span><br><span class="line">  timerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    p.then(flushCallbacks)</span><br><span class="line">    <span class="keyword">if</span> (isIOS) <span class="built_in">setTimeout</span>(noop)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Promise属于微任务，进行标识</span></span><br><span class="line">  isUsingMicroTask = <span class="literal">true</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (!isIE &amp;&amp; <span class="keyword">typeof</span> MutationObserver !== <span class="string">&#x27;undefined&#x27;</span> &amp;&amp; (</span><br><span class="line">  isNative(MutationObserver) ||</span><br><span class="line">  MutationObserver.toString() === <span class="string">&#x27;[object MutationObserverConstructor]&#x27;</span></span><br><span class="line">)) &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 判断是否支持MutationObsever</span></span><br><span class="line"><span class="comment">   */</span> </span><br><span class="line">  <span class="keyword">let</span> counter = <span class="number">1</span></span><br><span class="line">  <span class="comment">// 以MutationObsever的监听来处理flushCallbacks函数</span></span><br><span class="line">  <span class="keyword">const</span> observer = <span class="keyword">new</span> MutationObserver(flushCallbacks)</span><br><span class="line">  <span class="keyword">const</span> textNode = <span class="built_in">document</span>.createTextNode(<span class="built_in">String</span>(counter))</span><br><span class="line">  observer.observe(textNode, &#123;</span><br><span class="line">    characterData: <span class="literal">true</span></span><br><span class="line">  &#125;)</span><br><span class="line">  timerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    counter = (counter + <span class="number">1</span>) % <span class="number">2</span></span><br><span class="line">    textNode.data = <span class="built_in">String</span>(counter)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// MutationObsever也属于微任务，进行标识</span></span><br><span class="line">  isUsingMicroTask = <span class="literal">true</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> setImmediate !== <span class="string">&#x27;undefined&#x27;</span> &amp;&amp; isNative(setImmediate)) &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 判断是否支持setImmediate</span></span><br><span class="line"><span class="comment">   */</span> </span><br><span class="line">  timerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    setImmediate(flushCallbacks)</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 以上方法都不支持，则通过定时器的宏任务来处理</span></span><br><span class="line"><span class="comment">   */</span> </span><br><span class="line">  timerFunc = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(flushCallbacks, <span class="number">0</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对外暴露nextTick方法，传递callback回调函数，以及执行环境</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">nextTick</span> (<span class="params">cb?: <span class="built_in">Function</span>, ctx?: <span class="built_in">Object</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> _resolve</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 将回调函数包装后，放入callbacks数组</span></span><br><span class="line">  callbacks.push(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (cb) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        cb.call(ctx)</span><br><span class="line">      &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">        handleError(e, ctx, <span class="string">&#x27;nextTick&#x27;</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (_resolve) &#123;</span><br><span class="line">      _resolve(ctx)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (!pending) &#123;</span><br><span class="line">    <span class="comment">// 有微任务在执行时，先设置pending为true进行等待</span></span><br><span class="line">    pending = <span class="literal">true</span></span><br><span class="line">    timerFunc()</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如果支持Promise，对外返回Promise类型</span></span><br><span class="line">  <span class="keyword">if</span> (!cb &amp;&amp; <span class="keyword">typeof</span> <span class="built_in">Promise</span> !== <span class="string">&#x27;undefined&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="params">resolve</span> =&gt;</span> &#123;</span><br><span class="line">      _resolve = resolve</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="总结概述"><a href="#总结概述" class="headerlink" title="总结概述"></a>总结概述</h3><ul>
<li>整个<code>next-tick.js</code>文件对外只暴露一个<code>nextTick()</code>方法，方法的参数就是业务代码中的回调函数；</li>
<li>外部每调用一次<code>nextTick()</code>，传入的回调函数都会放入一个<code>callbacks</code>数组中，然后执行<code>timerFun()</code>异步方法；</li>
<li><code>timerFun()</code>对环境进行判断，是否支持微任务对象Promise/MutationObsever，如果不支持则通过setImmediate/setTimeout宏任务包装成异步方法，回调处理<code>flushCallbacks()</code>；</li>
<li><code>flushCallback()</code>如方法名所写，做的就是按顺序遍历执行每个回调函数，并清空数组；</li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://ustbhuangyi.github.io/vue-analysis/v2/reactive/next-tick.html#js-%E8%BF%90%E8%A1%8C%E6%9C%BA%E5%88%B6">https://ustbhuangyi.github.io/vue-analysis/v2/reactive/next-tick.html#js-%E8%BF%90%E8%A1%8C%E6%9C%BA%E5%88%B6</a></li>
<li><a target="_blank" rel="noopener" href="https://juejin.cn/post/6880710529355251726">https://juejin.cn/post/6880710529355251726</a> </li>
</ul>
<h2 id="未解决的疑惑"><a href="#未解决的疑惑" class="headerlink" title="未解决的疑惑"></a>未解决的疑惑</h2><ul>
<li>既然tick是指宏任务之间的间隔，<code>nextTick</code>为什么不直接放到下一个宏任务，而是优先放入微任务队列？</li>
<li><code>queueMicrotask()</code>也是往微任务队列中追加执行函数，<code>nextTick</code>为什么要用Promise来实现？</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/vue2_explore/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3nextTick/" title="深入理解nextTick">https://gitee.com/lianghuilin/murmur.git/vue2_explore/深入理解nextTick/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/interview_questions/js/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF%E6%9C%BA%E5%88%B6/" rel="prev" title="深入理解事件循环机制">
                  <i class="fa fa-chevron-left"></i> 深入理解事件循环机制
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/" rel="next" title="Vue3中ref模板引用的理解与实践">
                  Vue3中ref模板引用的理解与实践 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
